package dgut.haitaobao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import dgut.haitaobao.entry.Order;
import dgut.haitaobao.entry.ShoppingCart;
import dgut.haitaobao.mapper.OrderMapper;
import dgut.haitaobao.mapper.ShoppingCartMapper;
import dgut.haitaobao.service.OrderService;
import dgut.haitaobao.util.response.HttpResponse;
import dgut.haitaobao.vo.param.AddOrderParamsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    @Transactional
    public HttpResponse addOrderByUserId(AddOrderParamsVO paramsVO) {
        String userId = paramsVO.getUserId();
        List<String> cartIds = paramsVO.getCartIds();
        if (!CollectionUtils.isEmpty(cartIds)) {
            Order order=new Order();
            UpdateWrapper<ShoppingCart> updateWrapper=new UpdateWrapper<>();
            for (String cartId : cartIds) {
                //使购物车的记录物理删除
                updateWrapper.set("is_delete",1).eq("cart_id",cartId);
                shoppingCartMapper.update(null,updateWrapper);
                order.setUserId(Integer.parseInt(userId));
                order.setCartId(Integer.parseInt(cartId));
                order.setAddTime(new Date());
                orderMapper.insert(order);
            }
            return HttpResponse.success("添加订单成功");
        }else {
            return HttpResponse.error("添加订单失败");
        }

    }
}
